package com.rtos.vo.file.filetree;

import com.rtos.model.fileSystem.FileUtil;
import com.rtos.model.process.ProcessDispatcher;
import com.rtos.vo.file.diskPane.DiskViewer;
import com.rtos.vo.file.popFileContent.PopFileContent;
import com.rtos.vo.file.refresh.Refresh;
import javafx.scene.control.*;
import javafx.scene.input.MouseButton;

import java.util.ArrayList;
import java.util.Optional;

public class FileTrees {
    public TreeView FileTree;
    public FileUtil fileUtil;
    public DiskViewer diskViewer;
    public ProcessDispatcher processDispatcher;
    public FileTrees(TreeView FileTree, FileUtil fileUtil, DiskViewer diskViewer){
        this.FileTree = FileTree;
        this.processDispatcher= ProcessDispatcher.getInstance();
        this.fileUtil=fileUtil;
        this.diskViewer=diskViewer;
        TreeItem<String> root =new TreeItem<>("root");
        FileTree.setRoot(root);
        root.setExpanded(true);
        fileScnner("root",root);
        FileTree.setOnMouseClicked(event -> {
            MouseButton button = event.getButton();
            //单击操作
            if (button == MouseButton.PRIMARY) {
            }

            //右键点击
            if (button == MouseButton.SECONDARY) {
                addRightMenu();

            }

            //双击操作
            if (event.getClickCount() == 2) {

            }
        });

    }
    public void refresh(){
        TreeItem<String> root =new TreeItem<>("root");
        FileTree.setRoot(root);
        root.isExpanded();
        fileScnner("root",root);
    }
    public void TextData(){

        TreeItem<String> root =new TreeItem<>("root");
        TreeItem<String> a =new TreeItem<>("a");
        TreeItem<String> a1 =new TreeItem<>("a.exe");
        TreeItem<String> a2 = new TreeItem<>("b.exe");

        TreeItem<String> b =new TreeItem<>("b");
        TreeItem<String> b1 =new TreeItem<>("c.exe");
        TreeItem<String> b2 = new TreeItem<>("d.exe");

        TreeItem<String> FileInside =new TreeItem<>("file");

        FileTree.setRoot(root);

        a.getChildren().add(a1);
        a.getChildren().add(a2);
        a.getChildren().add(FileInside);

        b.getChildren().add(b1);
        b.getChildren().add(b2);

        root.getChildren().addAll(a,b);
        root.setExpanded(true);
        FileTree.setOnMouseClicked(event -> {
            MouseButton button = event.getButton();
            //单击操作
            if (button == MouseButton.PRIMARY) {
            }

            //右键点击
            if (button == MouseButton.SECONDARY) {
                addRightMenu();

            }

            //双击操作
            if (event.getClickCount() == 2) {

            }
        });
    }
    public void addRightMenu(){
//        if(FileTree.getSelectionModel().isEmpty())
        String s=(String) ((TreeItem)FileTree.getSelectionModel().getSelectedItem()).getValue();
        ContextMenu menu = new ContextMenu();
        MenuItem addFolders;
        MenuItem addFiles;
        MenuItem deleteItem;
        MenuItem edit;

        if(s.contains(".")){
            //不是文件夹
            deleteItem = new MenuItem("删除文件");
            edit  = new MenuItem("编辑文件");
            edit.setOnAction(e->{
                TreeItem selectItem = (TreeItem) FileTree.getSelectionModel().getSelectedItem();
                String nowPath=getPath(selectItem,"");
                int index = nowPath.indexOf("/");
                String nowPath0 = nowPath.substring(index+1);
                System.out.println("想编辑："+nowPath0);
//                try {
//                    fileUtil.modifyFile(nowPath0,"test");
//                } catch (Exception exception) {
//                    exception.printStackTrace();
//                }
                String fileContent = fileUtil.getFileContent(nowPath0);
                System.out.println(fileContent);
                PopFileContent popFileContent = new PopFileContent(fileContent,fileUtil,nowPath0,diskViewer);
            });
            menu.getItems().add(edit);
        }
        else {
            addFolders = new MenuItem("新建文件夹");
            addFiles = new MenuItem("新建文件");
            deleteItem = new MenuItem("删除文件夹");
            addFolders.setOnAction(e ->{
//            treeItem.getChildren().add(new TreeItem<>("文件夹" + treeItem.getChildren().size()));
                addFolder((TreeItem)FileTree.getSelectionModel().getSelectedItem());
            });
            menu.getItems().add(addFolders);

            addFiles.setOnAction(e ->{
//            treeItem.getChildren().add(new TreeItem<>("文件夹" + treeItem.getChildren().size()));
                addFile((TreeItem)FileTree.getSelectionModel().getSelectedItem());
            });
            menu.getItems().add(addFiles);
        }

        deleteItem.setOnAction(e ->{
            TreeItem selectItem = (TreeItem) FileTree.getSelectionModel().getSelectedItem();
            String nowPath=getPath(selectItem,"");
            int index = nowPath.indexOf("/");
            String nowPath0 = nowPath.substring(index+1);
            if(s.contains(".")){
                try {
                    System.out.println("想删除："+nowPath0);
                    if(nowPath0.contains("exe"))
                        if(processDispatcher.removeExeFile(nowPath0))
                            System.out.println("成功删除可执行文件");
                    fileUtil.deleteFile(nowPath0);

                    Refresh f=new Refresh(FileTree,fileUtil,diskViewer);

                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }
            else{
                try {
                    System.out.println("想删除："+nowPath0);

                    fileUtil.deleteAll(nowPath0);
                    Refresh f=new Refresh(FileTree,fileUtil,diskViewer);

                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }
            selectItem.getParent().getChildren().remove(selectItem);

        });

        menu.getItems().add(deleteItem);
        MenuItem rf;
        rf=new MenuItem("刷新");
        rf.setOnAction(e -> {
            refresh();
            //DiskViewer d;
          //  updateStatus
        });
        menu.getItems().add(rf);

        FileTree.setContextMenu(menu);
    }
    public void addFolder(TreeItem treeItem){
//        (String)treeItem.getParent();//
//        System.out.println("点击的是:"+treeItem .getParent().getValue());
        String nowPath=getPath(treeItem,"");
        System.out.println(nowPath);
        TextInputDialog dialog = new TextInputDialog("FOL");
        dialog.setTitle("新建项命名");
        dialog.setHeaderText(null);
        dialog.setContentText("请输入目录命名：");

        Optional<String> result = dialog.showAndWait();
        if (result.isPresent()){
            System.out.println("name: " + result.get());
            int index = nowPath.indexOf("/");
            String nowPath0 = nowPath.substring(index+1);
            //TreeItem<String> fileItem =new TreeItem<>(fileItemNext);
            try {
                System.out.println("添加："+nowPath0+"/"+result.get());
                fileUtil.makeDirectory(nowPath0+"/"+result.get());
            } catch (Exception e) {
                e.printStackTrace();
            }
            TreeItem<String> myFolder =new TreeItem<>(result.get());
            treeItem.getChildren().add(myFolder);
            Refresh f=new Refresh(FileTree,fileUtil,diskViewer);
        }
    }
    public void addFile(TreeItem treeItem){
        TextInputDialog dialog = new TextInputDialog(".exe");
        dialog.setTitle("新建项命名");
        dialog.setHeaderText(null);
        dialog.setContentText("请输入文件命名：");
//        dialog.
        String nowPath=getPath(treeItem,"");
        Optional<String> result = dialog.showAndWait();
        int f1=0;
        if (result.isPresent()){
            System.out.println("name: " + result.get());
            int index = nowPath.indexOf("/");
            String nowPath0 = nowPath.substring(index+1);
            try {
                System.out.println("添加："+nowPath0+"/"+result.get());
                 f1=fileUtil.createFile(nowPath0+"/"+result.get(),"x--\nend");
//                if(result.get().contains("exe"))


            } catch (Exception e) {
                e.printStackTrace();
            }
            if(f1==0){
                if( processDispatcher.addExeFile(nowPath0+"/"+result.get()))     System.out.println("成功添加可执行文件");
                TreeItem<String> myFile =new TreeItem<>(result.get());
                treeItem.getChildren().add(myFile);
                Refresh f=new Refresh(FileTree,fileUtil,diskViewer);
            }


        }
    }
    public void fileScnner(String nowPath,TreeItem PathItem){
        ArrayList<String> files = new ArrayList<String>();
        files = fileUtil.getDirectorysSimplified(nowPath);
//        System.out.println("myprint:");
        for (String file : files) {
           // file = file.replace("/","");
            if(file.contains(".")){
                //文件
                int index = file.lastIndexOf("/");
                String fileItemNext = file.substring(index+1);
                TreeItem<String> fileItem =new TreeItem<>(fileItemNext);
                System.out.println(fileItemNext);
                PathItem.getChildren().add(fileItem);
            }else{
                System.out.println(file);
//                String s = null;
                int index = file.lastIndexOf("/");
                String fileItemNext = file.substring(index+1);
                TreeItem<String> fileItem =new TreeItem<>(fileItemNext);
                PathItem.getChildren().add(fileItem);
                System.out.println(fileItemNext);
                fileScnner(file,fileItem);
            }
        }
    }
    public String getPath(TreeItem treeItem,String myPath){
        if(!(treeItem.getValue().equals("root"))){
            //treeItem=treeItem;
            //System.out.println("他爸是："+treeItem.getValue());
            myPath=getPath(treeItem.getParent(),"/"+treeItem.getValue()+myPath);
        }
        return myPath;
        // System.out.println("点击的是:"+treeItem .getParent().getValue());
    }
}
